// trades-modern.js
// Modern JS for trades page: modular, event-driven, fetch API, ES6+
document.addEventListener('DOMContentLoaded', () => {
    console.debug('[trades-modern.js] DOMContentLoaded');
    
    // 缓存symbol multipliers
    let symbolMultipliers = {};
    
    // 获取symbol multipliers
    fetch('/api/symbol_config')
        .then(resp => resp.json())
        .then(config => {
            console.debug('[trades-modern.js] symbol_config loaded:', config);
            symbolMultipliers = config;
        })
        .catch(err => {
            console.warn('[trades-modern.js] symbol_config fetch error:', err);
        })
        .then(() => {
            // 读取固定列配置（如果文件不存在则默认固定前3列）
            return fetch('/static/config/trades_page.json');
        })
        .then(resp => {
            console.debug('[trades-modern.js] trades_page.json fetch status:', resp.status);
            return resp.ok ? resp.json() : Promise.resolve({fixedColumns: [0,1,2]});
        })
        .catch(err => {
            console.warn('[trades-modern.js] trades_page.json fetch error:', err);
            return {fixedColumns: [0,1,2]};
        })
        .then(cfg => {
            console.debug('[trades-modern.js] trades_page.json config:', cfg);
            // 读取上次保存的每页条数
            let savedPageLength = 25;
            if (cfg.pageLength && !isNaN(cfg.pageLength)) {
                savedPageLength = parseInt(cfg.pageLength);
            }
            // 读取排序设置（列名+方向，需转为索引+方向）
            let savedOrder = [[0, 'desc']];
            if (cfg.order && Array.isArray(cfg.order)) {
                // 先构建列名到索引的映射
                const colNameToIndex = {};
                $('#tradesTable thead th').each(function(idx) {
                    const name = $(this).text().trim();
                    if (name && !(name in colNameToIndex)) {
                        colNameToIndex[name] = idx;
                    }
                });
                savedOrder = cfg.order.map(([colName, dir]) => {
                    const idx = colNameToIndex[colName];
                    return idx !== undefined ? [idx, dir] : [0, 'desc'];
                });
            }
            // 初始化 DataTable
            const table = $('#tradesTable').DataTable({
                order: savedOrder,
                pageLength: savedPageLength,
                language: {
                    sProcessing: '处理中...',
                    sLengthMenu: '显示 _MENU_ 项结果',
                    sZeroRecords: '没有匹配结果',
                    sInfo: '显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项',
                    sInfoEmpty: '显示第 0 至 0 项结果，共 0 项',
                    sInfoFiltered: '(由 _MAX_ 项结果过滤)',
                    sSearch: '搜索:',
                    oPaginate: {
                        sFirst: '首页',
                        sPrevious: '上页',
                        sNext: '下页',
                        sLast: '末页'
                    }
                },
                scrollX: true,
                scrollCollapse: true,
                dom: '<"top"Bfl>rt<"bottom"ip>',
                buttons: ['colvis', 'copy', 'excel', 'csv'],
                fixedColumns: false,
                colReorder: false,
                stateSave: false,
                fixedHeader: false,
                autoWidth: true,
                responsive: false,
                // 添加初始列可见性设置
                columnDefs: [
                    {
                        targets: 0, // 序号列
                        type: 'num' // 指定为数字类型，以便正确排序
                    },
                    {
                        targets: '_all',
                        visible: true
                    }
                ]
            });
            console.debug('[trades-modern.js] DataTable initialized');

            // 自动应用列显示/隐藏设置
            if (cfg.columnSettings) {
                console.debug('[trades-modern.js] Applying initial column settings:', cfg.columnSettings);
                Object.entries(cfg.columnSettings).forEach(([colName, visible]) => {
                    // 使用列名查找列
                    const column = table.column(function(idx, data, node) {
                        return $(node).text().trim() === colName;
                    });
                    if (column.length > 0) {  // 确保找到了列
                        column.visible(visible);
                        console.debug('[trades-modern.js] Set initial column visibility:', { colName, visible });
                    } else {
                        console.warn('[trades-modern.js] Column not found:', colName);
                    }
                });
            }

            // resize时自适应
            window.addEventListener('resize', () => {
                console.debug('[trades-modern.js] window resize');
                table.columns.adjust().draw(false);
            });
            // tab切换时自适应（如在Bootstrap Tab内）
            $(document).on('shown.bs.tab', function() {
                console.debug('[trades-modern.js] shown.bs.tab');
                setTimeout(() => table.columns.adjust().draw(false), 100);
            });
            // DataTables redraw后再次调整
            $('#tradesTable').on('draw.dt', function() {
                console.debug('[trades-modern.js] DataTable draw.dt');
                table.columns.adjust();
            });

            // 美化：开/平仓时间列内容居中、字体紧凑
            $('#tradesTable').on('draw.dt', function() {
                console.debug('[trades-modern.js] 美化开/平仓时间列');
                $('#tradesTable td:nth-child(3), #tradesTable td:nth-child(6)').css({
                    'text-align': 'center',
                    'font-size': '0.98em',
                    'padding': '0.35em 0.2em'
                });
            });

            // 行内编辑功能：点击 .editable 单元格变为输入框，回车/失焦提交
            $(document).off('click.editable');
            $(document).on('click.editable', '#tradesTable td.editable', function(e) {
                console.debug('[trades-modern.js] .editable cell clicked', this);
                e.stopPropagation();
                const cell = this;
                if (cell.querySelector('input')) return;
                const oldValue = cell.textContent.trim();
                const field = cell.dataset.field;
                const row = cell.closest('tr');
                const tradeId = row.dataset.tradeId;
                console.debug('[trades-modern.js] editable cell info', {field, tradeId, oldValue});
                if (!field || !tradeId) return;
                const input = document.createElement('input');
                input.type = (field.includes('price') || field.includes('points') || field.includes('dollars')) ? 'number' : 'text';
                input.step = (input.type === 'number') ? '0.01' : undefined;
                input.value = oldValue;
                input.className = 'form-control';
                input.style.width = '100%';
                cell.textContent = '';
                cell.appendChild(input);
                input.focus();
                $(cell).addClass('editing-cell');
                function save() {
                    const newValue = input.value;
                    console.debug('[trades-modern.js] editable save', {tradeId, field, oldValue, newValue});
                    
                    // Calculate corresponding dollar value if floating points are updated
                    let additionalFields = {};
                    if (field === 'max_floating_profit_points' || field === 'max_floating_loss_points') {
                        // 使用data-field属性获取数据
                        const symbolCell = row.querySelector('td[data-field="symbol"]');
                        const openQtyCell = row.querySelector('td[data-field="open_qty"]');
                        
                        console.debug('[trades-modern.js] row', row);
                        console.debug('[trades-modern.js] symbolCell, openQtyCell', symbolCell, openQtyCell);
                        
                        if (!symbolCell || !openQtyCell) {
                            console.warn('[trades-modern.js] Cannot find required cells for calculation', {
                                symbolCell: !!symbolCell,
                                openQtyCell: !!openQtyCell,
                                rowHtml: row.innerHTML
                            });
                            return;
                        }

                        const symbol = symbolCell.textContent.trim();
                        const openQty = openQtyCell.textContent.trim();
                        
                        if (!symbol || !openQty) {
                            console.warn('[trades-modern.js] Missing required values for calculation', {
                                symbol,
                                openQty
                            });
                            return;
                        }

                        // 从完整symbol中提取基础品种（例如从MESM25中提取MES）
                        const baseSymbol = symbol.length > 3 ? symbol.slice(0, -3) : symbol;
                        console.debug('[trades-modern.js] baseSymbol', baseSymbol);
                        const multiplier = symbolMultipliers[baseSymbol]?.multiplier || 1.0;
                        console.debug('[trades-modern.js] symbolMultipliers', symbolMultipliers);
                        if (field === 'max_floating_profit_points') {
                            additionalFields = {
                                max_floating_profit_dollars: (parseFloat(newValue) * parseInt(openQty) * multiplier).toFixed(2)
                            };
                        } else {
                            additionalFields = {
                                max_floating_loss_dollars: (parseFloat(newValue) * parseInt(openQty) * multiplier).toFixed(2)
                            };
                        }
                    }

                    // Prepare the request body with all fields to update
                    const body = new URLSearchParams({ trade_id: tradeId, field, value: newValue });
                    Object.entries(additionalFields).forEach(([key, value]) => {
                        body.append(key, value);
                    });

                    fetch('/update_trade', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                        body: body
                    }).then(r => r.json()).then(resp => {
                        console.debug('[trades-modern.js] editable save resp', resp);
                        if (resp.success) {
                            cell.textContent = newValue;
                            $(cell).addClass('cell-updated');
                            setTimeout(() => $(cell).removeClass('cell-updated'), 600);
                            
                            // Update the corresponding dollar value cell if it exists
                            if (field === 'max_floating_profit_points' && additionalFields.max_floating_profit_dollars) {
                                const dollarCell = row.querySelector('td[data-field="max_floating_profit_dollars"]');
                                if (dollarCell) {
                                    dollarCell.textContent = additionalFields.max_floating_profit_dollars;
                                    $(dollarCell).addClass('cell-updated');
                                    setTimeout(() => $(dollarCell).removeClass('cell-updated'), 600);
                                }
                            } else if (field === 'max_floating_loss_points' && additionalFields.max_floating_loss_dollars) {
                                const dollarCell = row.querySelector('td[data-field="max_floating_loss_dollars"]');
                                if (dollarCell) {
                                    dollarCell.textContent = additionalFields.max_floating_loss_dollars;
                                    $(dollarCell).addClass('cell-updated');
                                    setTimeout(() => $(dollarCell).removeClass('cell-updated'), 600);
                                }
                            }
                            
                                                            // 如果更新的是RRR、FWR、Actual Risk或PRR相关字段，需要刷新计算字段的显示
                                if (['take_profit_price', 'stop_loss_price', 'point_profit_per_lot', 'max_floating_profit_points', 'max_floating_loss_points', 'extend', 'exit_reason'].includes(field)) {
                                console.debug('[trades-modern.js] RRR/FWR/Actual Risk/PRR related field updated, refreshing calculated fields');
                                // 重新获取交易数据以更新计算字段
                                fetch('/trades_api')
                                    .then(r => r.json())
                                    .then(trades => {
                                        const updatedTrade = trades.find(t => t.trade_id === tradeId);
                                        if (updatedTrade) {
                                            // 更新OR字段
                                            const orCell = row.querySelector('td[data-field="open_rrr"]');
                                            if (orCell && updatedTrade.open_rrr !== null && updatedTrade.open_rrr !== '') {
                                                orCell.textContent = parseFloat(updatedTrade.open_rrr).toFixed(2);
                                                $(orCell).addClass('cell-updated');
                                                setTimeout(() => $(orCell).removeClass('cell-updated'), 600);
                                            }
                                            
                                            // 更新CR字段
                                            const crCell = row.querySelector('td[data-field="close_rrr"]');
                                            if (crCell && updatedTrade.close_rrr !== null && updatedTrade.close_rrr !== '') {
                                                crCell.textContent = parseFloat(updatedTrade.close_rrr).toFixed(2);
                                                $(crCell).addClass('cell-updated');
                                                setTimeout(() => $(crCell).removeClass('cell-updated'), 600);
                                            }
                                            
                                            // 更新FWR字段
                                            const fwrCell = row.querySelector('td[data-field="fwr"]');
                                            if (fwrCell && updatedTrade.fwr !== null && updatedTrade.fwr !== '') {
                                                fwrCell.textContent = parseFloat(updatedTrade.fwr).toFixed(2);
                                                $(fwrCell).addClass('cell-updated');
                                                setTimeout(() => $(fwrCell).removeClass('cell-updated'), 600);
                                            }
                                            
                                            // 更新Actual Risk字段
                                            const actualRiskCell = row.querySelector('td[data-field="actual_risk"]');
                                            if (actualRiskCell && updatedTrade.actual_risk !== null && updatedTrade.actual_risk !== '') {
                                                actualRiskCell.textContent = parseFloat(updatedTrade.actual_risk).toFixed(2);
                                                $(actualRiskCell).addClass('cell-updated');
                                                setTimeout(() => $(actualRiskCell).removeClass('cell-updated'), 600);
                                            }
                                            
                                            // 更新PRR字段
                                            const prrCell = row.querySelector('td[data-field="prr"]');
                                            if (prrCell && updatedTrade.prr !== null && updatedTrade.prr !== '') {
                                                prrCell.textContent = parseFloat(updatedTrade.prr).toFixed(2);
                                                $(prrCell).addClass('cell-updated');
                                                setTimeout(() => $(prrCell).removeClass('cell-updated'), 600);
                                            }
                                        }
                                    })
                                    .catch(err => {
                                        console.warn('[trades-modern.js] Failed to refresh calculated values:', err);
                                    });
                            }
                        } else {
                            cell.textContent = oldValue;
                            alert('更新失败: ' + resp.message);
                        }
                        $(cell).removeClass('editing-cell');
                    }).catch(err => {
                        console.warn('[trades-modern.js] editable save error', err);
                        cell.textContent = oldValue;
                        $(cell).removeClass('editing-cell');
                        alert('更新失败');
                    });
                }
                input.addEventListener('blur', save);
                input.addEventListener('keydown', function(e) { if (e.key === 'Enter') save(); });
            });

            // Column Settings: Save changes 按钮逻辑（防止多复选框指向同一列导致死循环）
            $('#saveColumnSettings').off('click').on('click', function() {
                console.debug('[trades-modern.js] Save Column Settings clicked');
                const $modal = $('#columnSettingsModal');
                const $button = $(this);
                
                // 禁用保存按钮，防止重复点击
                $button.prop('disabled', true);
                
                try {
                    // 保存列设置到 localStorage
                    const columnSettings = {};
                    $('.column-toggle').each(function() {
                        const colName = $(this).val();
                        columnSettings[colName] = $(this).is(':checked');
                    });
                    localStorage.setItem('trades_column_settings', JSON.stringify(columnSettings));
                    
                    // 应用列设置
                    Object.entries(columnSettings).forEach(([colName, visible]) => {
                        // 使用列名查找列
                        const column = table.column(function(idx, data, node) {
                            return $(node).text().trim() === colName;
                        });
                        column.visible(visible);
                        console.debug('[trades-modern.js] Set column visibility:', { colName, visible });
                    });
                    
                    // 保存列设置到后端
                    fetch('/save_column_settings', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ columnSettings })
                    })
                    .then(resp => resp.json())
                    .then(data => {
                        console.debug('[trades-modern.js] columnSettings saved to backend:', data);
                        // 失焦所有元素
                        if (document.activeElement) document.activeElement.blur();
                        
                        // 关闭模态框前确保所有状态都已保存
                        $modal.modal('hide');
                    })
                    .catch(err => {
                        console.warn('[trades-modern.js] columnSettings save to backend failed:', err);
                        alert('保存设置失败，请重试');
                    })
                    .finally(() => {
                        // 重新启用保存按钮
                        $button.prop('disabled', false);
                    });
                } catch (error) {
                    console.error('[trades-modern.js] Error in save column settings:', error);
                    alert('保存设置时发生错误，请重试');
                    $button.prop('disabled', false);
                }
            });

            // 在模态框显示前确保清理之前的状态并同步复选框状态
            $('#columnSettingsModal').on('show.bs.modal', function () {
                console.debug('[trades-modern.js] show.bs.modal triggered');
                const $modal = $(this);
                
                // 确保之前的遮罩被清理
                $('.modal-backdrop').remove();
                $('body').removeClass('modal-open');
                
                // 重置模态框状态
                if ($modal.data('bs.modal')) {
                    $modal.data('bs.modal').isShown = false;
                }

                // 同步复选框状态与实际的列可见性状态
                $('.column-toggle').each(function() {
                    const colName = $(this).val();
                    // 使用列名查找列
                    const column = table.column(function(idx, data, node) {
                        return $(node).text().trim() === colName;
                    });
                    const isVisible = column.visible();
                    $(this).prop('checked', isVisible);
                    console.debug('[trades-modern.js] Synced checkbox state:', { colName, isVisible });
                });
            });

            // 在模态框完全隐藏后进行清理，防止遮罩残留和页面卡死
            $('#columnSettingsModal').on('hidden.bs.modal', function () {
                console.debug('[trades-modern.js] hidden.bs.modal triggered');
                const $modal = $(this);
                
                // 确保模态框的aria-hidden属性被重置
                $modal.removeAttr('aria-hidden');
                // 移除body上的modal-open类
                $('body').removeClass('modal-open');
                // 移除所有modal-backdrop
                $('.modal-backdrop').remove();
                
                // 重置模态框状态
                $modal.data('bs.modal', null);
            });

            // 在模态框显示后确保状态正确
            $('#columnSettingsModal').on('shown.bs.modal', function () {
                console.debug('[trades-modern.js] shown.bs.modal triggered');
                const $modal = $(this);
                
                // 确保模态框可见
                $modal.css('display', 'block');
                $modal.addClass('show');
                
                // 确保遮罩层正确显示
                if (!$('.modal-backdrop').length) {
                    $('body').append('<div class="modal-backdrop fade show"></div>');
                }
            });

            // 读取 trade_config.json 配置，加载完成后再绑定下拉事件（只绑定一次，缓存选项）
            let tradeConfig = null;
            let selectOptionsCache = {};
            fetch('/api/trade_config')
                .then(resp => {
                    console.debug('[trades-modern.js] trade_config.json fetch status:', resp.status);
                    return resp.ok ? resp.json() : Promise.resolve({});
                })
                .catch(err => {
                    console.warn('[trades-modern.js] trade_config.json fetch error:', err);
                    return {};
                })
                .then(cfg => {
                    tradeConfig = cfg;
                    console.debug('[trades-modern.js] trade_config.json config:', tradeConfig);
                    // 缓存所有下拉选项
                    if (tradeConfig) {
                        selectOptionsCache['trade_type'] = [''].concat(tradeConfig.trade_types || []);
                        selectOptionsCache['entry_reason'] = [''].concat(tradeConfig.entry_reasons || []);
                        selectOptionsCache['exit_reason'] = [''].concat(tradeConfig.exit_reasons || []);
                        selectOptionsCache['stop_loss_reason'] = [''].concat(tradeConfig.stop_loss_reasons || []);
                        selectOptionsCache['take_profit_reason'] = [''].concat(tradeConfig.stop_loss_reasons || []);
                        selectOptionsCache['side'] = [''].concat(tradeConfig.side_options || []);
                        selectOptionsCache['rating'] = ['', '1', '2', '3', '4', '5'];
                        console.debug('[trades-modern.js] selectOptionsCache:', JSON.stringify(selectOptionsCache, null, 2));
                    }
                    // 只绑定一次事件
                    $(document).off('click.editableSelect');
                    $(document).on('click.editableSelect', '#tradesTable td.editable-select', function(e) {
                        console.debug('[trades-modern.js] .editable-select cell clicked', this);
                        e.stopPropagation();
                        const cell = this;
                        if (cell.querySelector('select')) return;
                        const oldValue = cell.textContent.trim();
                        const field = cell.dataset.field;
                        const row = cell.closest('tr');
                        const tradeId = row.dataset.tradeId;
                        console.debug('[trades-modern.js] editable-select cell info', {field, tradeId, oldValue});
                        if (!field || !tradeId) return;
                        // 直接用缓存的 options
                        let options = selectOptionsCache[field];
                        if (!Array.isArray(options) || options.length === 0) {
                            options = [''];
                        }
                        // 止盈理由（tp_reason）如果配置为"复用止损理由"，则用 stop_loss_reasons
                        //if (field === 'tp_reason' && Array.isArray(selectOptionsCache['tp_reason']) && selectOptionsCache['tp_reason'].length === 1 && selectOptionsCache['tp_reason'][0] === '复用止损理由' && Array.isArray(selectOptionsCache['sl_reason'])) {
                        //    options = [''].concat(selectOptionsCache['sl_reason'].slice(1));
                        //}
                        // 只有 options 非空且 oldValue 非空且不在 options 时才补充 oldValue
                        // if (options.length > 1 && oldValue && !options.includes(oldValue)) {
                        //     options = options.concat([oldValue]);
                        // }
                        console.debug('[trades-modern.js] editable-select options', options);
                        const select = document.createElement('select');
                        select.className = 'form-select';
                        select.style.width = '100%';
                        options.forEach(opt => {
                            const option = document.createElement('option');
                            option.value = opt;
                            option.textContent = opt === '' ? '' : opt;
                            if (opt === oldValue) option.selected = true;
                            select.appendChild(option);
                        });
                        cell.textContent = '';
                        cell.appendChild(select);
                        select.focus();
                        $(cell).addClass('editing-cell');
                        select.addEventListener('change', save);
                        select.addEventListener('blur', save);
                        function save() {
                            const newValue = select.value;
                            console.debug('[trades-modern.js] editable-select save', {tradeId, field, oldValue, newValue});
                            fetch('/update_trade', {
                                method: 'POST',
                                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                                body: new URLSearchParams({ trade_id: tradeId, field, value: newValue })
                            }).then(r => r.json()).then(resp => {
                                console.debug('[trades-modern.js] editable-select save resp', resp);
                                if (resp.success) {
                                    cell.textContent = newValue;
                                    $(cell).addClass('cell-updated');
                                    setTimeout(() => $(cell).removeClass('cell-updated'), 600);
                                } else {
                                    cell.textContent = oldValue;
                                    alert('更新失败: ' + resp.message);
                                }
                                $(cell).removeClass('editing-cell');
                            }).catch(err => {
                                console.warn('[trades-modern.js] editable-select save error', err);
                                cell.textContent = oldValue;
                                $(cell).removeClass('editing-cell');
                                alert('更新失败');
                            });
                        }
                    });
                });

            // 行背景色根据净利润设置（通过列名查找更准确）
            $('#tradesTable').on('draw.dt', function() {
                // 获取所有表头列名
                const colNames = [];
                $('#tradesTable thead th').each(function() {
                    colNames.push($(this).text().trim());
                });
                // 查找净利润列索引
                let netProfitIdx = colNames.findIndex(name => name.includes('净利润') || name.toLowerCase().includes('net_profit'));
                console.debug('[trades-modern.js] netProfitIdx', netProfitIdx);
                console.debug('[trades-modern.js] colNames', colNames);
                if (netProfitIdx === -1) return;
                $('#tradesTable tbody tr').each(function() {
                    const $row = $(this);
                    const netProfitText = $row.find('td').eq(netProfitIdx).text().replace(/,/g, '');
                    const netProfit = parseFloat(netProfitText);
                    console.debug('[trades-modern.js] netProfitText', netProfitText);
                    console.debug('[trades-modern.js] netProfit', netProfit);
                    // 先移除所有相关背景色class
                    $row.removeClass('profit-bg-deepred profit-bg-lightred profit-bg-yellow profit-bg-lightgreen profit-bg-deepgreen profit-bg-blue');
                    if (!isNaN(netProfit)) {
                        if (netProfit < -500) $row.addClass('profit-bg-purple');
                        else if (netProfit < -250) $row.addClass('profit-bg-deepred');
                        else if (netProfit < -25) $row.addClass('profit-bg-lightred');
                        else if (netProfit < 25) $row.addClass('profit-bg-yellow');
                        else if (netProfit < 250) $row.addClass('profit-bg-lightgreen');
                        else if (netProfit < 500) $row.addClass('profit-bg-deepgreen');
                        else $row.addClass('profit-bg-blue');
                    }
                });
            });
            // 手动触发一次，确保初始渲染有颜色
            $('#tradesTable').trigger('draw.dt');

            // 监听每页条数变化并保存到后端
            table.on('length.dt', function(e, settings, len) {
                // 读取当前列设置
                const columnSettings = {};
                $('#tradesTable thead th').each(function(idx) {
                    const name = $(this).text().trim();
                    if (name) {
                        columnSettings[name] = table.column(idx).visible();
                    }
                });
                // 读取当前排序（列名+方向）
                const currentOrder = table.order().map(([colIdx, dir]) => {
                    const colName = $('#tradesTable thead th').eq(colIdx).text().trim();
                    return [colName, dir];
                });
                fetch('/save_column_settings', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ columnSettings, pageLength: len, order: currentOrder })
                }).then(resp => resp.json())
                  .then(data => {
                      console.debug('[trades-modern.js] pageLength saved to backend:', data);
                  }).catch(err => {
                      console.warn('[trades-modern.js] pageLength save to backend failed:', err);
                  });
            });

            // 监听排序变化并保存到后端
            table.on('order.dt', function(e, settings) {
                // 读取当前排序（列名+方向）
                const currentOrder = table.order().map(([colIdx, dir]) => {
                    const colName = $('#tradesTable thead th').eq(colIdx).text().trim();
                    return [colName, dir];
                });
                // 读取当前列设置
                const columnSettings = {};
                $('#tradesTable thead th').each(function(idx) {
                    const name = $(this).text().trim();
                    if (name) {
                        columnSettings[name] = table.column(idx).visible();
                    }
                });
                // 读取当前每页条数
                const pageLength = table.page.len();
                fetch('/save_column_settings', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ columnSettings, pageLength, order: currentOrder })
                }).then(resp => resp.json())
                  .then(data => {
                      console.debug('[trades-modern.js] order saved to backend:', data);
                  }).catch(err => {
                      console.warn('[trades-modern.js] order save to backend failed:', err);
                  });
            });
        });
});
